/**
 * $Id: Parser.java 20 2006-09-16 20:32:08Z willi.w $
 */
package at.wwu.tunes2db;

import java.io.*;

import org.apache.log4j.Logger;
import org.xml.sax.*;
import org.xml.sax.helpers.XMLReaderFactory;

import at.wwu.tunes2db.export.Profiler;
import at.wwu.tunes2db.xml.LibraryContentHandler;

/**
 * @author willi.w
 * open the .xml file, set the handler, parse it
 */
public class Parser {
    private static final Logger log = Logger.getLogger(Parser.class.getName());
    
    XMLReader reader = null;
    ContentHandler libContentHandler = null;
    ErrorHandler libErrorHandler = null;
    InputSource source = null;
    File bib = null;
    InputStreamReader filestreamreader = null;
    public Parser(Commandline cmd, ContentHandler ch, ErrorHandler eh) throws SAXException, FileNotFoundException {
        reader = XMLReaderFactory.createXMLReader();
        reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        reader.setFeature("http://xml.org/sax/features/validation", false);
        bib = new File(cmd.getInput());
        bib.setReadOnly();
        try {
            filestreamreader = new InputStreamReader(new FileInputStream(bib), "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        libContentHandler = ch;
        libErrorHandler = eh;
        source = new InputSource(filestreamreader);
    }
    public void parse() throws IOException, SAXException {
        reader.setContentHandler(libContentHandler);
        try {
            reader.parse(source);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            log.fatal(e.getMessage()+" at track "+Profiler.getInstance().getLastTrack());
        }
        reader.toString();
    }
}

